import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../services/mcp_service.dart';
import '../models/mcp_tool.dart';
import '../widgets/custom_title_bar.dart';
import 'dart:convert';

/// 简化版 MCP 测试页面
class SimpleTestScreen extends StatefulWidget {
  const SimpleTestScreen({Key? key}) : super(key: key);

  @override
  State<SimpleTestScreen> createState() => _SimpleTestScreenState();
}

class _SimpleTestScreenState extends State<SimpleTestScreen> {
  final McpService _mcpService = McpService();
  final TextEditingController _urlController = TextEditingController(text: '');

  List<McpTool> _tools = [];
  McpTool? _selectedTool;
  Map<String, TextEditingController> _paramControllers = {};
  Map<String, dynamic> _parameters = {};

  bool _isConnected = false;
  bool _isLoading = false;
  String _status = '未连接';
  final List<String> _logs = [];
  String? _lastResult;
  final ScrollController _logScrollController = ScrollController();
  bool _autoScroll = true; // 是否自动滚动到最新日志
  bool _showScrollToBottom = false; // 是否显示"跳到最新"按钮

  // 可调整大小的参数
  double _logPanelHeight = 200;
  final double _minLogHeight = 100;
  final double _maxLogHeight = 600;

  @override
  void initState() {
    super.initState();
    // 监听滚动位置，检测用户是否手动滚动
    _logScrollController.addListener(_onLogScroll);
  }

  @override
  void dispose() {
    _logScrollController.removeListener(_onLogScroll);
    _mcpService.dispose();
    _urlController.dispose();
    _logScrollController.dispose();
    _disposeParamControllers();
    super.dispose();
  }

  void _onLogScroll() {
    if (!_logScrollController.hasClients) return;

    final isAtBottom =
        _logScrollController.position.pixels >=
        _logScrollController.position.maxScrollExtent - 50;

    // 如果用户滚动到底部，恢复自动滚动
    if (isAtBottom) {
      if (!_autoScroll) {
        setState(() {
          _autoScroll = true;
          _showScrollToBottom = false;
        });
      }
    } else {
      // 用户手动向上滚动，暂停自动滚动
      if (_autoScroll) {
        setState(() {
          _autoScroll = false;
          _showScrollToBottom = true;
        });
      }
    }
  }

  void _scrollToBottom() {
    if (_logScrollController.hasClients) {
      _logScrollController.animateTo(
        _logScrollController.position.maxScrollExtent,
        duration: const Duration(milliseconds: 300),
        curve: Curves.easeOut,
      );
      setState(() {
        _autoScroll = true;
        _showScrollToBottom = false;
      });
    }
  }

  void _disposeParamControllers() {
    for (var controller in _paramControllers.values) {
      controller.dispose();
    }
    _paramControllers.clear();
  }

  void _log(String message) {
    setState(() {
      _logs.add('${DateTime.now().toString().substring(11, 23)} $message');
    });
    print(message);

    // 只有在自动滚动模式下才滚动到底部
    if (_autoScroll) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        if (_logScrollController.hasClients) {
          _logScrollController.animateTo(
            _logScrollController.position.maxScrollExtent,
            duration: const Duration(milliseconds: 300),
            curve: Curves.easeOut,
          );
        }
      });
    } else {
      // 如果不是自动滚动，确保显示"跳到最新"按钮
      if (!_showScrollToBottom) {
        setState(() {
          _showScrollToBottom = true;
        });
      }
    }
  }

  Future<void> _connect() async {
    setState(() {
      _isLoading = true;
      _status = '连接中...';
      _logs.clear();
    });

    _log('🔄 开始连接: ${_urlController.text}');

    try {
      final config = McpConfig(
        type: McpConnectionType.sse,
        sseUrl: _urlController.text,
      );

      await _mcpService.configure(config);
      _log('✅ 连接成功');

      setState(() {
        _isConnected = true;
        _status = '已连接';
      });

      // 自动获取工具列表
      await _loadTools();
    } catch (e) {
      _log('❌ 连接失败: $e');
      setState(() {
        _status = '连接失败';
        _isConnected = false;
      });
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  Future<void> _disconnect() async {
    _log('🔌 断开连接');
    await _mcpService.disconnect();
    setState(() {
      _isConnected = false;
      _status = '已断开';
      _tools.clear();
      _selectedTool = null;
      _lastResult = null;
    });
  }

  Future<void> _loadTools() async {
    _log('🔧 开始获取工具列表...');
    setState(() {
      _isLoading = true;
      _status = '加载工具中...';
    });

    try {
      final tools = await _mcpService.listTools();
      _log('✅ 获取到 ${tools.length} 个工具');

      for (var tool in tools) {
        _log('   - ${tool.name}');
      }

      setState(() {
        _tools = tools;
        _status = '已加载 ${tools.length} 个工具';
      });
    } catch (e) {
      _log('❌ 获取工具失败: $e');
      setState(() {
        _status = '加载失败';
      });
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  void _onToolSelected(McpTool tool) {
    _log('📌 选择工具: ${tool.name}');
    setState(() {
      _selectedTool = tool;
      _lastResult = null;
      _parameters.clear();
    });
    _initializeParameters(tool);
  }

  void _initializeParameters(McpTool tool) {
    _disposeParamControllers();
    _paramControllers.clear();
    _parameters.clear();

    for (var param in tool.parameters) {
      final controller = TextEditingController();
      _paramControllers[param.name] = controller;

      // 设置默认值
      if (param.defaultValue != null) {
        if (param.defaultValue is String) {
          controller.text = param.defaultValue;
        } else {
          controller.text = param.defaultValue.toString();
        }
        _parameters[param.name] = param.defaultValue;
      }
    }
  }

  void _updateParameter(String name, String value, String type) {
    // 根据类型转换参数值
    dynamic convertedValue;

    if (value.isEmpty) {
      _parameters.remove(name);
      return;
    }

    try {
      switch (type.toLowerCase()) {
        case 'number':
        case 'integer':
          convertedValue = num.parse(value);
          break;
        case 'boolean':
          convertedValue = value.toLowerCase() == 'true';
          break;
        case 'array':
        case 'object':
          // 尝试解析 JSON
          convertedValue = jsonDecode(value);
          break;
        default:
          convertedValue = value;
      }
      _parameters[name] = convertedValue;
    } catch (e) {
      // 解析失败，使用字符串
      _parameters[name] = value;
    }
  }

  Future<void> _callTool() async {
    if (_selectedTool == null) return;

    // 验证必需参数
    for (var param in _selectedTool!.parameters) {
      if (param.required && !_parameters.containsKey(param.name)) {
        _showErrorDialog('参数验证失败', '必需参数 "${param.name}" 未填写');
        return;
      }
    }

    _log('🧪 调用工具: ${_selectedTool!.name}');
    _log('   参数: ${jsonEncode(_parameters)}');

    setState(() {
      _isLoading = true;
      _lastResult = null;
    });

    try {
      final result = await _mcpService.callTool(
        _selectedTool!.name,
        _parameters,
      );

      if (result.success) {
        _log('✅ 工具调用成功');
        final resultJson = _formatJson(result.result);
        _log('   结果: $resultJson');
        setState(() {
          _lastResult = resultJson;
        });
      } else {
        _log('❌ 工具调用失败: ${result.error}');
        setState(() {
          _lastResult = '错误: ${result.error}';
        });
      }
    } catch (e) {
      _log('❌ 调用异常: $e');
      setState(() {
        _lastResult = '异常: $e';
      });
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  String _formatJson(dynamic data) {
    try {
      const encoder = JsonEncoder.withIndent('  ');
      return encoder.convert(data);
    } catch (e) {
      return data.toString();
    }
  }

  void _showErrorDialog(String title, String message) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text(title),
        content: Text(message),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('确定'),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [
          // 自定义标题栏
          CustomTitleBar(
            title: 'MCP 工具测试工具',
            actions: [
              if (_isConnected)
                IconButton(
                  icon: const Icon(Icons.refresh, size: 18),
                  onPressed: _isLoading ? null : _loadTools,
                  tooltip: '刷新工具列表',
                ),
              IconButton(
                icon: const Icon(Icons.copy, size: 18),
                onPressed: () {
                  final logsText = _logs.join('\n');
                  Clipboard.setData(ClipboardData(text: logsText));
                  ScaffoldMessenger.of(
                    context,
                  ).showSnackBar(const SnackBar(content: Text('日志已复制')));
                },
                tooltip: '复制日志',
              ),
            ],
          ),

          // 连接配置
          _buildConnectionBar(),

          // 主内容区域
          Expanded(
            child: Row(
              children: [
                // 左侧：工具列表
                SizedBox(width: 280, child: _buildToolsList()),

                // 中间：参数配置和调用
                Expanded(flex: 2, child: _buildParameterPanel()),

                // 右侧：结果和日志
                Expanded(flex: 3, child: _buildResultAndLogPanel()),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildConnectionBar() {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.grey[100],
        border: Border(bottom: BorderSide(color: Colors.grey[300]!)),
      ),
      child: Row(
        children: [
          Expanded(
            child: TextField(
              controller: _urlController,
              decoration: const InputDecoration(
                labelText: 'MCP 服务器地址',
                border: OutlineInputBorder(),
                prefixIcon: Icon(Icons.link),
                isDense: true,
                contentPadding: EdgeInsets.symmetric(
                  horizontal: 12,
                  vertical: 8,
                ),
              ),
              enabled: !_isLoading && !_isConnected,
            ),
          ),
          const SizedBox(width: 16),
          ElevatedButton.icon(
            onPressed: _isLoading
                ? null
                : (_isConnected ? _disconnect : _connect),
            icon: Icon(_isConnected ? Icons.close : Icons.play_arrow),
            label: Text(_isConnected ? '断开' : '连接'),
            style: ElevatedButton.styleFrom(
              backgroundColor: _isConnected ? Colors.red : Colors.blue,
              foregroundColor: Colors.white,
              padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
            ),
          ),
          const SizedBox(width: 16),
          Icon(
            _isConnected ? Icons.check_circle : Icons.radio_button_unchecked,
            color: _isConnected ? Colors.green : Colors.grey,
          ),
          const SizedBox(width: 8),
          Text(
            _status,
            style: TextStyle(
              fontWeight: FontWeight.bold,
              color: _isConnected ? Colors.green : Colors.grey[700],
            ),
          ),
          if (_isLoading) ...[
            const SizedBox(width: 16),
            const SizedBox(
              width: 20,
              height: 20,
              child: CircularProgressIndicator(strokeWidth: 2),
            ),
          ],
        ],
      ),
    );
  }

  Widget _buildToolsList() {
    return Container(
      decoration: BoxDecoration(
        border: Border(right: BorderSide(color: Colors.grey[300]!)),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            padding: const EdgeInsets.all(16),
            decoration: BoxDecoration(
              color: Colors.grey[50],
              border: Border(bottom: BorderSide(color: Colors.grey[300]!)),
            ),
            child: Row(
              children: [
                const Icon(Icons.build, size: 20),
                const SizedBox(width: 8),
                Text(
                  '工具列表 (${_tools.length})',
                  style: const TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ],
            ),
          ),
          Expanded(
            child: _tools.isEmpty
                ? Center(
                    child: Text(
                      _isConnected ? '没有可用工具' : '请先连接服务器',
                      style: TextStyle(color: Colors.grey[600]),
                    ),
                  )
                : ListView.builder(
                    itemCount: _tools.length,
                    itemBuilder: (context, index) {
                      final tool = _tools[index];
                      final isSelected = _selectedTool == tool;
                      return Tooltip(
                        message: _buildToolTooltip(tool),
                        preferBelow: false,
                        verticalOffset: 20,
                        padding: const EdgeInsets.all(12),
                        decoration: BoxDecoration(
                          color: Colors.grey[900],
                          borderRadius: BorderRadius.circular(8),
                          boxShadow: [
                            BoxShadow(
                              color: Colors.black.withOpacity(0.3),
                              blurRadius: 8,
                              offset: const Offset(0, 4),
                            ),
                          ],
                        ),
                        textStyle: const TextStyle(
                          color: Colors.white,
                          fontSize: 13,
                          height: 1.5,
                        ),
                        waitDuration: const Duration(milliseconds: 500),
                        child: Container(
                          decoration: BoxDecoration(
                            color: isSelected ? Colors.blue[50] : null,
                            border: Border(
                              bottom: BorderSide(
                                color: Colors.grey[200]!,
                                width: 0.5,
                              ),
                            ),
                          ),
                          child: ListTile(
                            dense: true,
                            leading: Icon(
                              Icons.extension,
                              size: 20,
                              color: isSelected
                                  ? Colors.blue
                                  : Colors.grey[600],
                            ),
                            title: Text(
                              tool.name,
                              style: TextStyle(
                                fontSize: 14,
                                fontWeight: isSelected
                                    ? FontWeight.bold
                                    : FontWeight.normal,
                              ),
                            ),
                            subtitle: Text(
                              tool.description,
                              maxLines: 2,
                              overflow: TextOverflow.ellipsis,
                              style: const TextStyle(fontSize: 12),
                            ),
                            onTap: () => _onToolSelected(tool),
                          ),
                        ),
                      );
                    },
                  ),
          ),
        ],
      ),
    );
  }

  Widget _buildParameterPanel() {
    return Container(
      decoration: BoxDecoration(
        border: Border(right: BorderSide(color: Colors.grey[300]!)),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          // 标题
          Container(
            padding: const EdgeInsets.all(16),
            decoration: BoxDecoration(
              color: Colors.grey[50],
              border: Border(bottom: BorderSide(color: Colors.grey[300]!)),
            ),
            child: Row(
              children: [
                const Icon(Icons.tune, size: 20),
                const SizedBox(width: 8),
                Text(
                  _selectedTool == null
                      ? '参数配置'
                      : '${_selectedTool!.name} - 参数配置',
                  style: const TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ],
            ),
          ),

          // 参数表单
          Expanded(
            child: _selectedTool == null
                ? Center(
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Icon(
                          Icons.arrow_back,
                          size: 48,
                          color: Colors.grey[400],
                        ),
                        const SizedBox(height: 16),
                        Text(
                          '← 请从左侧选择一个工具',
                          style: TextStyle(
                            fontSize: 16,
                            color: Colors.grey[600],
                          ),
                        ),
                      ],
                    ),
                  )
                : SingleChildScrollView(
                    padding: const EdgeInsets.all(16),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.stretch,
                      children: [
                        // 工具描述
                        if (_selectedTool!.description.isNotEmpty) ...[
                          Container(
                            padding: const EdgeInsets.all(12),
                            decoration: BoxDecoration(
                              color: Colors.blue[50],
                              border: Border.all(color: Colors.blue[200]!),
                              borderRadius: BorderRadius.circular(8),
                            ),
                            child: Row(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Icon(
                                  Icons.info_outline,
                                  size: 20,
                                  color: Colors.blue[700],
                                ),
                                const SizedBox(width: 8),
                                Expanded(
                                  child: Text(
                                    _selectedTool!.description,
                                    style: TextStyle(
                                      color: Colors.blue[900],
                                      fontSize: 13,
                                    ),
                                  ),
                                ),
                              ],
                            ),
                          ),
                          const SizedBox(height: 24),
                        ],

                        // 参数表单
                        if (_selectedTool!.parameters.isEmpty)
                          Center(
                            child: Padding(
                              padding: const EdgeInsets.all(32),
                              child: Column(
                                children: [
                                  Icon(
                                    Icons.check_circle_outline,
                                    size: 48,
                                    color: Colors.green[300],
                                  ),
                                  const SizedBox(height: 16),
                                  Text(
                                    '此工具无需参数',
                                    style: TextStyle(
                                      fontSize: 14,
                                      color: Colors.grey[600],
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          )
                        else
                          ..._selectedTool!.parameters.map((param) {
                            return Padding(
                              padding: const EdgeInsets.only(bottom: 16),
                              child: _buildParameterField(param),
                            );
                          }).toList(),

                        const SizedBox(height: 24),

                        // 调用按钮
                        ElevatedButton.icon(
                          onPressed: _isLoading ? null : _callTool,
                          icon: _isLoading
                              ? const SizedBox(
                                  width: 16,
                                  height: 16,
                                  child: CircularProgressIndicator(
                                    strokeWidth: 2,
                                    valueColor: AlwaysStoppedAnimation<Color>(
                                      Colors.white,
                                    ),
                                  ),
                                )
                              : const Icon(Icons.play_arrow),
                          label: Text(_isLoading ? '执行中...' : '执行工具'),
                          style: ElevatedButton.styleFrom(
                            padding: const EdgeInsets.symmetric(vertical: 16),
                            backgroundColor: Colors.green,
                            foregroundColor: Colors.white,
                            textStyle: const TextStyle(
                              fontSize: 16,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
          ),
        ],
      ),
    );
  }

  Widget _buildParameterField(McpToolParameter param) {
    final controller = _paramControllers[param.name]!;

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          children: [
            Expanded(
              child: Text(
                param.name,
                style: const TextStyle(
                  fontSize: 14,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
            if (param.required)
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
                decoration: BoxDecoration(
                  color: Colors.red[100],
                  borderRadius: BorderRadius.circular(4),
                ),
                child: Text(
                  '必需',
                  style: TextStyle(
                    fontSize: 11,
                    color: Colors.red[900],
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ),
            const SizedBox(width: 8),
            Container(
              padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
              decoration: BoxDecoration(
                color: Colors.grey[200],
                borderRadius: BorderRadius.circular(4),
              ),
              child: Text(
                param.type,
                style: TextStyle(
                  fontSize: 11,
                  color: Colors.grey[700],
                  fontFamily: 'monospace',
                ),
              ),
            ),
          ],
        ),
        if (param.description != null) ...[
          const SizedBox(height: 4),
          Text(
            param.description!,
            style: TextStyle(fontSize: 12, color: Colors.grey[600]),
          ),
        ],
        const SizedBox(height: 8),

        // 根据类型选择不同的输入控件
        if (param.type.toLowerCase() == 'boolean')
          _buildBooleanField(param, controller)
        else if (param.enumValues != null && param.enumValues!.isNotEmpty)
          _buildEnumField(param, controller)
        else if (param.type.toLowerCase() == 'object' ||
            param.type.toLowerCase() == 'array')
          _buildJsonField(param, controller)
        else
          _buildTextField(param, controller),
      ],
    );
  }

  Widget _buildTextField(
    McpToolParameter param,
    TextEditingController controller,
  ) {
    return TextField(
      controller: controller,
      decoration: InputDecoration(
        hintText: param.defaultValue?.toString() ?? '请输入${param.name}',
        border: const OutlineInputBorder(),
        isDense: true,
        contentPadding: const EdgeInsets.all(12),
      ),
      keyboardType:
          param.type.toLowerCase() == 'number' ||
              param.type.toLowerCase() == 'integer'
          ? TextInputType.number
          : TextInputType.text,
      onChanged: (value) => _updateParameter(param.name, value, param.type),
    );
  }

  Widget _buildBooleanField(
    McpToolParameter param,
    TextEditingController controller,
  ) {
    bool value = controller.text.toLowerCase() == 'true';

    return Row(
      children: [
        Expanded(
          child: RadioListTile<bool>(
            title: const Text('True', style: TextStyle(fontSize: 14)),
            value: true,
            groupValue: value,
            dense: true,
            contentPadding: EdgeInsets.zero,
            onChanged: (val) {
              if (val != null) {
                setState(() {
                  controller.text = 'true';
                  _parameters[param.name] = true;
                });
              }
            },
          ),
        ),
        Expanded(
          child: RadioListTile<bool>(
            title: const Text('False', style: TextStyle(fontSize: 14)),
            value: false,
            groupValue: value,
            dense: true,
            contentPadding: EdgeInsets.zero,
            onChanged: (val) {
              if (val != null) {
                setState(() {
                  controller.text = 'false';
                  _parameters[param.name] = false;
                });
              }
            },
          ),
        ),
      ],
    );
  }

  Widget _buildEnumField(
    McpToolParameter param,
    TextEditingController controller,
  ) {
    return DropdownButtonFormField<String>(
      value: controller.text.isEmpty ? null : controller.text,
      decoration: const InputDecoration(
        border: OutlineInputBorder(),
        isDense: true,
        contentPadding: EdgeInsets.all(12),
      ),
      hint: Text('请选择${param.name}'),
      items: param.enumValues!.map((value) {
        return DropdownMenuItem(value: value, child: Text(value));
      }).toList(),
      onChanged: (value) {
        if (value != null) {
          setState(() {
            controller.text = value;
            _updateParameter(param.name, value, param.type);
          });
        }
      },
    );
  }

  Widget _buildJsonField(
    McpToolParameter param,
    TextEditingController controller,
  ) {
    return TextField(
      controller: controller,
      decoration: InputDecoration(
        hintText: param.type.toLowerCase() == 'array'
            ? '["item1", "item2"]'
            : '{"key": "value"}',
        border: const OutlineInputBorder(),
        isDense: true,
        contentPadding: const EdgeInsets.all(12),
        helperText: '请输入有效的 JSON 格式',
        helperStyle: TextStyle(fontSize: 11, color: Colors.grey[600]),
      ),
      maxLines: 3,
      style: const TextStyle(fontFamily: 'monospace', fontSize: 12),
      onChanged: (value) => _updateParameter(param.name, value, param.type),
    );
  }

  Widget _buildResultAndLogPanel() {
    return Column(
      children: [
        // 结果区域
        Expanded(
          child: Container(
            decoration: BoxDecoration(
              border: Border(bottom: BorderSide(color: Colors.grey[300]!)),
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: [
                Container(
                  padding: const EdgeInsets.all(16),
                  decoration: BoxDecoration(
                    color: Colors.grey[50],
                    border: Border(
                      bottom: BorderSide(color: Colors.grey[300]!),
                    ),
                  ),
                  child: Row(
                    children: [
                      const Icon(Icons.receipt_long, size: 20),
                      const SizedBox(width: 8),
                      const Text(
                        '执行结果',
                        style: TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      const Spacer(),
                      if (_lastResult != null)
                        IconButton(
                          icon: const Icon(Icons.copy, size: 18),
                          onPressed: () {
                            Clipboard.setData(
                              ClipboardData(text: _lastResult!),
                            );
                            ScaffoldMessenger.of(context).showSnackBar(
                              const SnackBar(content: Text('结果已复制')),
                            );
                          },
                          tooltip: '复制结果',
                        ),
                    ],
                  ),
                ),
                Expanded(
                  child: _lastResult == null
                      ? Center(
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Icon(
                                Icons.play_circle_outline,
                                size: 64,
                                color: Colors.grey[300],
                              ),
                              const SizedBox(height: 16),
                              Text(
                                '执行工具后结果将显示在这里',
                                style: TextStyle(
                                  fontSize: 14,
                                  color: Colors.grey[600],
                                ),
                              ),
                            ],
                          ),
                        )
                      : Container(
                          color: Colors.grey[50],
                          padding: const EdgeInsets.all(16),
                          child: SingleChildScrollView(
                            child: SelectableText(
                              _lastResult!,
                              style: const TextStyle(
                                fontFamily: 'monospace',
                                fontSize: 12,
                              ),
                            ),
                          ),
                        ),
                ),
              ],
            ),
          ),
        ),

        // 可拖动的分隔器
        GestureDetector(
          onVerticalDragUpdate: (details) {
            setState(() {
              _logPanelHeight = (_logPanelHeight - details.delta.dy).clamp(
                _minLogHeight,
                _maxLogHeight,
              );
            });
          },
          child: MouseRegion(
            cursor: SystemMouseCursors.resizeRow,
            child: Container(
              height: 8,
              decoration: BoxDecoration(
                color: Colors.grey[300],
                border: Border(
                  top: BorderSide(color: Colors.grey[400]!),
                  bottom: BorderSide(color: Colors.grey[400]!),
                ),
              ),
              child: Center(
                child: Container(
                  width: 40,
                  height: 3,
                  decoration: BoxDecoration(
                    color: Colors.grey[500],
                    borderRadius: BorderRadius.circular(2),
                  ),
                ),
              ),
            ),
          ),
        ),

        // 日志区域
        SizedBox(
          height: _logPanelHeight,
          child: Stack(
            children: [
              Container(
                color: Colors.black,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.stretch,
                  children: [
                    Container(
                      padding: const EdgeInsets.all(12),
                      decoration: const BoxDecoration(color: Color(0xFF1E1E1E)),
                      child: Row(
                        children: [
                          const Icon(
                            Icons.terminal,
                            color: Colors.white,
                            size: 16,
                          ),
                          const SizedBox(width: 8),
                          const Text(
                            '调试日志',
                            style: TextStyle(
                              color: Colors.white,
                              fontWeight: FontWeight.bold,
                              fontSize: 13,
                            ),
                          ),
                          const Spacer(),
                          // 自动滚动状态指示器
                          Container(
                            padding: const EdgeInsets.symmetric(
                              horizontal: 8,
                              vertical: 4,
                            ),
                            decoration: BoxDecoration(
                              color: _autoScroll
                                  ? Colors.green.withOpacity(0.2)
                                  : Colors.grey.withOpacity(0.2),
                              borderRadius: BorderRadius.circular(4),
                            ),
                            child: Row(
                              mainAxisSize: MainAxisSize.min,
                              children: [
                                Icon(
                                  _autoScroll ? Icons.play_arrow : Icons.pause,
                                  color: _autoScroll
                                      ? Colors.greenAccent
                                      : Colors.grey,
                                  size: 12,
                                ),
                                const SizedBox(width: 4),
                                Text(
                                  _autoScroll ? '自动' : '暂停',
                                  style: TextStyle(
                                    color: _autoScroll
                                        ? Colors.greenAccent
                                        : Colors.grey,
                                    fontSize: 11,
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ],
                      ),
                    ),
                    Expanded(
                      child: _logs.isEmpty
                          ? const Center(
                              child: Text(
                                '暂无日志',
                                style: TextStyle(color: Colors.grey),
                              ),
                            )
                          : ListView.builder(
                              controller: _logScrollController,
                              padding: const EdgeInsets.all(8),
                              itemCount: _logs.length,
                              itemBuilder: (context, index) {
                                final log = _logs[index];
                                Color textColor = Colors.white;

                                if (log.contains('✅') || log.contains('成功')) {
                                  textColor = Colors.greenAccent;
                                } else if (log.contains('❌') ||
                                    log.contains('失败')) {
                                  textColor = Colors.redAccent;
                                } else if (log.contains('⚠️')) {
                                  textColor = Colors.orangeAccent;
                                } else if (log.contains('🔧') ||
                                    log.contains('🧪')) {
                                  textColor = Colors.yellowAccent;
                                } else if (log.contains('📡') ||
                                    log.contains('📤') ||
                                    log.contains('📥')) {
                                  textColor = Colors.cyanAccent;
                                }

                                return Padding(
                                  padding: const EdgeInsets.symmetric(
                                    vertical: 2,
                                  ),
                                  child: SelectableText(
                                    log,
                                    style: TextStyle(
                                      color: textColor,
                                      fontFamily: 'monospace',
                                      fontSize: 11,
                                    ),
                                  ),
                                );
                              },
                            ),
                    ),
                  ],
                ),
              ),

              // "跳到最新"悬浮按钮
              if (_showScrollToBottom)
                Positioned(
                  right: 16,
                  bottom: 16,
                  child: Material(
                    color: Colors.transparent,
                    child: InkWell(
                      onTap: _scrollToBottom,
                      borderRadius: BorderRadius.circular(24),
                      child: Container(
                        padding: const EdgeInsets.symmetric(
                          horizontal: 16,
                          vertical: 10,
                        ),
                        decoration: BoxDecoration(
                          color: Colors.blue[700],
                          borderRadius: BorderRadius.circular(24),
                          boxShadow: [
                            BoxShadow(
                              color: Colors.black.withOpacity(0.3),
                              blurRadius: 8,
                              offset: const Offset(0, 4),
                            ),
                          ],
                        ),
                        child: Row(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            const Icon(
                              Icons.arrow_downward,
                              color: Colors.white,
                              size: 16,
                            ),
                            const SizedBox(width: 6),
                            const Text(
                              '跳到最新',
                              style: TextStyle(
                                color: Colors.white,
                                fontSize: 12,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ),
                ),
            ],
          ),
        ),
      ],
    );
  }

  String _buildToolTooltip(McpTool tool) {
    final buffer = StringBuffer();

    // 工具名称
    buffer.writeln('🔧 ${tool.name}');
    buffer.writeln();

    // 工具描述
    if (tool.description.isNotEmpty) {
      buffer.writeln('📝 描述：');
      buffer.writeln(tool.description);
      buffer.writeln();
    }

    // 参数列表
    if (tool.parameters.isNotEmpty) {
      buffer.writeln('⚙️ 参数：');
      for (var param in tool.parameters) {
        final required = param.required ? ' (必需)' : ' (可选)';
        buffer.write('  • ${param.name}$required');
        buffer.writeln(' - ${param.type}');

        if (param.description != null && param.description!.isNotEmpty) {
          buffer.writeln('    ${param.description}');
        }

        if (param.defaultValue != null) {
          buffer.writeln('    默认值: ${param.defaultValue}');
        }

        if (param.enumValues != null && param.enumValues!.isNotEmpty) {
          buffer.writeln('    可选值: ${param.enumValues!.join(", ")}');
        }
      }
    } else {
      buffer.writeln('⚙️ 无需参数');
    }

    buffer.writeln();
    buffer.write('💡 点击选择该工具');

    return buffer.toString();
  }
}
